/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.util;

import java.util.*;

public class CommonUtils {
    // 合并两个hashmap；并用right覆盖left
    public static Map<String, Object> merge(Map<String, Object> base, Map<String, Object> ow) {
        Map<String, Object> result = new HashMap<>();
        if (base == null && ow == null) {
            return null;
        }
        if (base != null) {
            result.putAll(base);
        }
        if (ow != null) {
            result.putAll(ow);
        }
        return result;
    }

    // 函数范型：支持各种类型的字段合并
    public static <T> T merge(T base, T ow) {
        T result = base;
        if (ow != null) {
            result = ow;
        }
        return result;
    }

    // 对象cast为List结构
    public static List<Object> castObj2List(Object obj) {
        List<Object> list = new ArrayList<>();
        if (obj.getClass().isArray()) {
            list = Arrays.asList((Object[])obj);
        }
        return list;
    }

    // 判断list中是否包含指定key
    public static boolean contains(List<String> list, String key) {
        if (list.contains(key)) {
            return true;
        } else {
            return false;
        }
    }

    // 判断map中是否包含指定key
    public static boolean contains(Map<String, List<String>> map, String key) {
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            for (String list : entry.getValue()) {
                if (list.contains(key)) {
                    return true;
                }
            }
        }
        return false;
    }
}
